package com.example.personalmemo.recordInfo;

import com.example.personalmemo.ResourceTable;
import com.example.personalmemo.dataName.DataAbilityName;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

import java.util.List;

public class MyItem extends BaseItemProvider {

    private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0, "Demo");

    List<RecordInfo> list;
    Context context;
    DataAbilityHelper dataAbilityHelper;
    DataAbilityPredicates predicates;


    public MyItem(List<RecordInfo> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public int getCount() {
        HiLog.info(LABEL_LOG, "getCount");
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        HiLog.info(LABEL_LOG, "getItem");
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        HiLog.info(LABEL_LOG, "getItemId");
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        HiLog.info(LABEL_LOG, "getComponent");
        final Component cpt;
        if (component == null) {
            cpt = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item, null, false);
        } else {
            cpt = component;
        }

        RecordInfo record = list.get(i);
        Text title = cpt.findComponentById(ResourceTable.Id_title_text);
        Text time = cpt.findComponentById(ResourceTable.Id_time_text);
        Component remove = cpt.findComponentById(ResourceTable.Id_all_remove);

        title.setText(record.getTitle());
        time.setText(record.getTime());

        // 点击删除
        remove.setClickedListener(component1 -> {
            del(i);
        });

        return cpt;
    }

    // 删除记录
    private void del(int index) {
        dataAbilityHelper = DataAbilityHelper.create(context);
        RecordInfo record = (RecordInfo) getItem(index);
        Integer did = record.getId();
        if (did != null && !"".equals(did)) {
            predicates = new DataAbilityPredicates();
            predicates.equalTo("id", did);
            try {
                //数据库里删除
                int i = dataAbilityHelper.delete(Uri.parse(DataAbilityName.DATA_URI + "/infodata/delList"), predicates);
                if (i != -1) {

                }
                //更新集合
                list.remove(index);
                //通知订阅者更新数据
                notifyDataChanged();
            } catch (DataAbilityRemoteException e) {
                e.printStackTrace();
            }

        }


    }

    public void setList(List<RecordInfo> list) {
        this.list = list;
    }


}
